<template>
  <!-- 导入基本数据 -->
  <a-modal
    :visible="importExeclVisible"
    title="农户数据待确认表"
    centered
    :closable="false"
    width="80%"
    dialogClass='member-execl-dialog'
    @cancel="importExeclVisible = false"
  >
    <ImportExeclPreview
      :execlData="execlData"
      :isMember="isMember"
      ref="ImportExeclPreview"
    />
    <section slot="footer">
      <a-button @click="importExeclVisible = false">取消</a-button>
      <!-- <a-button
        type="primary"
        :loading="importExeclConfirmLoading"
        @click="handlerConfirmImport(1)"
      >{{ isPreview ? '待上传文件内容已确认' : '覆盖导入' }}</a-button> -->
      <a-button
        type="primary"
        :loading="importExeclConfirmLoading"
        @click="handlerConfirmImport(0)"
      >{{ isPreview ? '待上传文件内容已确认' : '增量导入' }}</a-button>
    </section>
  </a-modal>
</template>

<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator'
import { ImportExecl } from '@/utils/execl'
import { famerServices, IMember } from '@/common/services/famer'
import ImportExeclPreview from './MemberImportExeclPreview.vue'
import MemberImportErrors from './MemberImportErrors.vue'
import { message, Modal } from 'ant-design-vue'
import { BUSINESS_CODE } from '@/api/interceptors'
import { isIDCard } from '@/utils/tools'

@Component({
  components: {
    ImportExeclPreview,
    MemberImportErrors
  }
})
export default class MemberImportMixin extends Vue {
  @Prop({
    type: Boolean,
    default: false
  })
  public isPreview!: boolean

  @Prop({
    type: String
  })
  public currentAreaId!: string

  // 上传execl
  public importExeclVisible = false
  public importExeclConfirmLoading = false
  public execlData: any[] = []
  public file!: File
  public isMember: boolean = true
  public handlerUploadExecl(isMember: boolean = true) {
    const _self = this
    this.isMember = isMember
    let fields: Record<string, string> = {
      zt: '是否加入补贴',
      s_a_id: '行政地区编号',
      member_id: '农户编号',
      member_nam: '户主姓名',
      member_sfz: '身份证号',
      family_book_id: '户口本编号',
      member_sex: '性别',
      member_tel: '手机号',
      member_bank_num: '银行卡号',
      member_bank_code: '开户银行',
      member_addr: '家庭住址',
      // @ts-ignore
      field: '耕地面积（亩）',
      // field: [
      //   '耕地面积（亩）',
      //   '确权面积（亩）'
      // ],
      // @ts-ignore
      field1: [
        '承包地',
        '基础面积'
      ],
      field2: '增加面积',
      field3: '减少面积',
      plant: '粮食种植面积（亩）',
      field_confirm_t: '确权面积（亩）',
      field_confirm: '二包面积（亩）',
      field_tax: '计税面积（亩）',
      readme: '备注'
    }
    ImportExecl(fields, (data, map) => {
      console.log(data, map)
      // 提取表头信息
      const [first, second] = data.slice(0, 2)
      let tempFields = Object.assign({}, second, first)

      for (const i in tempFields) {
        let value = tempFields[i]
        tempFields[value] = i
        delete tempFields[i]
      }

      for (const i in fields) {
        const field = fields[i]
        let hasKey
        /**
         * @todo 支持字段传数组，字段变动兼容逻辑，命中优先级在数组内从左到右
        */
        if (Array.isArray(field)) {
          const item = field.find(item => tempFields[item]);
          hasKey = tempFields[item];
        } else {
          hasKey = tempFields[field];
        }
        if (hasKey) {
          fields[i] = hasKey
        }
      }

      data = data.slice(2)
      // 剔除行首无效数据
      // 行政编码：是数字，长度大于6
      if (data.length) {
        while (
          data[0] &&
          !(
            data[0][fields['s_a_id']] &&
            `${data[0][fields['s_a_id']]}`.length >= 6 &&
            !isNaN(+data[0][fields['s_a_id']])
          )
        ) {
          data.shift()
        }
      }

      return {
        fields: fields,
        data
      }
    }).then(_ => {
      this.importExeclVisible = true
      // @ts-ignore
      this.execlData = this.formatIDCardError(_.formatedData) || []
      // @ts-ignore
      this.file = _.file
    })
  }

  public formatIDCardError(data: any[]) {
    return data.map(item => {
      if (!isIDCard(item.member_sfz)) {
        return {
          ...item,
          error: true
        }
      }
      return item
    })
  }

  public handlerConfirmImport(type: number = 0) {
    this.$confirm({
      title: '导入提示',
      content:
        type === 0
          ? '本次导入数据将更新或追加到当前选择行政区，确认导入？'
          : '本次导入数据将替换当前选择行政区数据（原数据将被删除，不能在线恢复），确认导入？',
      onOk: () => {
        this.handlerImport(type)
      }
    })
  }

  public async handlerImport(type: number) {
    // @ts-ignore
    const data = this.$refs.ImportExeclPreview.execlData
    if (!data.length) {
      message.error('请导入数据')
      return false
    }

    // 预览模式下直接返回数据 + 关闭
    if (this.isPreview) {
      this.$emit('previewSuccess', {
        data,
        file: this.file
      })
      this.importExeclVisible = false
      return
    }

    this.importExeclConfirmLoading = true

    famerServices
      .importExecl({
        data,
        file_nam: this.file.name,
        s_a_id: this.currentAreaId,
        type
      })
      .then(_ => {
        const res = _.data
        if (res.code === BUSINESS_CODE.SUCCESS) {
          Modal.success({
            content: res.data || '数据导入成功',
            centered: true
          })
        } else {
          this.$dialog(
            MemberImportErrors,
            {
              messages: res.msg.map(str => ({ content: str }))
            },
            {
              title: '异常农户数据列表',
              width: '60%',
              footer: null
            }
          )
          // message.error({
          //   content: res.msg
          // })
        }
      })
      .finally(() => {
        this.importExeclVisible = false
        this.importExeclConfirmLoading = false
      })
  }
}
</script>

<style lang="less" scoped>
.member-container {
  display: flex;
  .area-tree {
    width: 300px;
    flex: none;
    background-color: #fff;
    border-right: 1px solid #eee;
    margin-right: 10px;
  }
}
.house-holder /deep/ .ant-card-body {
  max-height: 600px;
  height: auto;
}
.member-list {
  display: flex;
  flex-direction: column;
}
</style>
